<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, h, ref } from 'vue'
import { Page, useVbenModal } from '@vben/common-ui'
import { Button, message, Tag, Popconfirm } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getDownloadRecordList, downloadFile, exportDownloadData } from '#/api/downloadRecord'
import { useUserStore, useSiteStore } from '@vben/stores'

import dayjs from 'dayjs'
import Form from './modules/form.vue'
import { AntPlusOutlined, AntDownloadOutlined } from '@vben/icons'

interface RowType {
  id: number
  admin: {
    id?: number
    realname?: string
  }
  title?: string
  total_num?: number
  progress?: number
  down_status?: number
  start_time?: string
  end_time?: string
  created_at?: string
  admin_id?: number
  file_url?: string
  [key: string]: any
}

const selectedRows = ref<RowType[]>([])
const userStore = useUserStore()

// 默认排序
const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'id',
  order: 'desc',
}

const fetchData = async () => {
  gridApi.reload()
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-4',
  schema: [
    {
      component: 'Input',
      fieldName: 'title',
      label: '标题',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'admin*realname',
      label: '创建用户',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'down_status',
      label: '状态',
      operator: '=',
      componentProps: {
        options: [
          { label: '待完成', value: 0 },
          { label: '已完成', value: 1 },
          { label: '停止下载', value: 3 },
          { label: '错误', value: 9 },
        ],
        placeholder: '请选择',
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    isHover: true,
  },
  columnConfig: {
    useKey: true,
  },
  columns: [
    { type: 'checkbox', width: 50, fixed: 'left' },
    { field: 'id', width: 70, title: '序号', fixed: 'left' },
    { field: 'admin.realname', width: 150, title: '创建用户', fixed: 'left' },
    { field: 'title', minWidth: 150, title: '标题' },
    { field: 'total_num', width: 120, title: '总数量' },
    { field: 'progress', width: 80, title: '进度' },
    {
      field: 'down_status',
      width: 120,
      title: '状态',
      slots: { default: 'status' },
    },
    {
      field: 'start_time',
      width: 160,
      title: '执行开始时间',
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
        }
        return '-'
      },
    },
    {
      field: 'end_time',
      width: 160,
      title: '执行结束时间',
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
        }
        return '-'
      },
    },
    {
      field: 'created_at',
      width: 160,
      title: '创建时间',
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
        }
        return '-'
      },
    },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 120,
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 20,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }, formValues) => {
        const search = await gridApi.formApi.getFiltersValues()
        const res = await getDownloadRecordList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        })

        return {
          items: res.list,
          total: res.total,
        }
      },
    },
    sort: true,
  },
  sortConfig: {
    defaultSort,
    remote: true,
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'download_record_list',
  customConfig: {
    storage: true,
  },
}

// 获取状态标签颜色
const getStatusColor = (status: number) => {
  switch (status) {
    case 0:
      return 'default'
    case 1:
      return 'success'
    case 3:
      return 'warning'
    case 9:
      return 'error'
    default:
      return 'default'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '待完成'
    case 1:
      return '已完成'
    case 3:
      return '停止下载'
    case 9:
      return '错误'
    default:
      return '未知'
  }
}

// 是否可以下载文件
const canDownload = (row: RowType) => {
  return row.down_status === 1 && row.admin_id === userStore.userInfo?.id
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    }
  },
})

// 下载文件
const handleDownloadFile = (row: RowType) => {
  if (!canDownload(row)) {
    message.error('不是本人文件或文件未完成')
    return
  }
  if (row.file_url) {
    window.location.href = row.file_url
  } else {
    message.error('文件路径不存在')
  }
}

// 导出功能
const handleExport = async () => {
  const hide = message.loading('正在导出...', 0)
  try {
    const search = await gridApi.formApi.getFiltersValues()
    await exportDownloadData({ search })
  } catch (e) {
    message.error('导出失败')
  } finally {
    hide()
  }
}

// 事件处理
const handleshowFormData = (row?: RowType) => {
  FormModalApi.setData({
    info: row || {},
  }).open()
}

const [FormModal, FormModalApi] = useVbenModal({
  connectedComponent: Form,
})
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <!-- <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleshowFormData()">
          <AntPlusOutlined />
          新建
        </Button>
      </template> -->

      <template #status="{ row }">
        <Tag :color="getStatusColor(row.down_status)">
          {{ getStatusText(row.down_status) }}
        </Tag>
      </template>

      <template #operation="{ row }">
        <Button type="ghost" size="small" :class="['mr-2', !canDownload(row) ? 'ant-btn-disabled' : 'bg-[#1cb317] text-white hover:opacity-75']" :disabled="!canDownload(row)" @click.stop="handleDownloadFile(row)">
          <AntDownloadOutlined />
          下载文件
        </Button>
      </template>
    </Grid>
    <FormModal @fetch-data="fetchData" />
  </Page>
</template>
